﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ComponentModel;
using System.IO;

namespace AzureDriverExplorer_Client
{
    /// <summary>
    /// Interaction logic for AddConnection.xaml
    /// </summary>
    public partial class AddConnection : Page
    {
        private Const cons = new Const();
        private System.Resources.ResourceManager ResManager;
           
        public AddConnection()
        {
            InitializeComponent();
         
            try
            {
                if (!File.Exists(Const.FileConfig))
                { File.Create(Const.FileConfig); }
                else
                {
                    try
                    {
                        // Create an instance of StreamReader to read from a file.
                        // The using statement also closes the StreamReader.
                        using (StreamReader sr = new StreamReader(Const.FileConfig))
                        {
                            String line;
                            // Read and display lines from the file until the end of 
                            // the file is reached.
                            List<VHDDataConfig> ListConfig = new List<VHDDataConfig>();
                            while ((line = sr.ReadLine()) != null)
                            {
                                try
                                {
                                    string[] vecListConfig = line.Split(' ');
                                    VHDDataConfig GetListConfig = new VHDDataConfig(vecListConfig[0], vecListConfig[1], vecListConfig[2], vecListConfig[3]);

                                    ListConfig.Add(GetListConfig);
                                }
                                catch { }
                            }
                            ListConnection.ItemsSource = ListConfig;
                        }
                    }
                    catch (Exception ex)
                    {
                        // Let the user know what went wrong.
                        MessageBox.Show(ex.Message, string.Empty, MessageBoxButton.OK, MessageBoxImage.Error);

                    }
                }
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message + "[" + (Const.FileConfig) + "]", string.Empty, MessageBoxButton.OK, MessageBoxImage.Error); }

            AddConnectionLanguage();
        }
        private void AddConnectionLanguage()
        {

             ResManager = new System.Resources.ResourceManager("AzureDriverExplorer_Client.Properties.Resources", this.GetType().Assembly);



            AccountName.Content = ResManager.GetString("AccountName" + cons.Language).Trim();
            AccountKey.Header = ResManager.GetString("AccountKey" + cons.Language).Trim();
            ContainerName.Header = ResManager.GetString("ContainerName" + cons.Language).Trim();
            VHDName.Header = ResManager.GetString("VHDName" + cons.Language).Trim();

            AddElementTitle.Text = ResManager.GetString("AddElement" + cons.Language).Trim();
            AccountNameTitle.Text = ResManager.GetString("AccountName" + cons.Language).Trim();
            AccountKeyTitle.Text = ResManager.GetString("AccountKey" + cons.Language).Trim();
            ContainerNameTitle.Text = ResManager.GetString("ContainerName" + cons.Language).Trim();
            VHDNameTitle.Text = ResManager.GetString("VHDName" + cons.Language).Trim();

            Add.Content = ResManager.GetString("Add" + cons.Language).Trim();
            AddClear.Content = ResManager.GetString("Clear" + cons.Language).Trim();
            AddCancel.Content = ResManager.GetString("Cancel" + cons.Language).Trim();

            EditElementTitle.Text = ResManager.GetString("EditElement" + cons.Language).Trim();
            EditAccountNameTitle.Text = ResManager.GetString("AccountName" + cons.Language).Trim();
            EditAccountKeyTitle.Text = ResManager.GetString("AccountKey" + cons.Language).Trim();
            EditContainerNameTitle.Text = ResManager.GetString("ContainerName" + cons.Language).Trim();
            EditVHDNameTitle.Text = ResManager.GetString("VHDName" + cons.Language).Trim();

            Edit.Content = ResManager.GetString("Edit" + cons.Language).Trim();
            EditClear.Content = ResManager.GetString("Clear" + cons.Language).Trim();
            EditCancel.Content = ResManager.GetString("Cancel" + cons.Language).Trim();
        }

        private void ShowPopup(object sender, RoutedEventArgs e)
        {
            popupAdd.Visibility = Visibility.Visible;

        }



        private GridViewColumnHeader _CurSortCol = null;
        private SortAdorner _CurAdorner = null;

        /// <summary>
        /// ListViewLocalのshort
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SortLocalClick(object sender, RoutedEventArgs e)
        {

            GridViewColumnHeader column = sender as GridViewColumnHeader;
            string field = column.Tag as string;

            if (_CurSortCol != null)
            {
                AdornerLayer.GetAdornerLayer(_CurSortCol).Remove(_CurAdorner);
                ListConnection.Items.SortDescriptions.Clear();
            }

            ListSortDirection newDir = ListSortDirection.Ascending;
            if (_CurSortCol == column && _CurAdorner.Direction == newDir)
                newDir = ListSortDirection.Descending;
            else
                newDir = ListSortDirection.Ascending;


            _CurSortCol = column;
            _CurAdorner = new SortAdorner(_CurSortCol, newDir);
            AdornerLayer.GetAdornerLayer(_CurSortCol).Add(_CurAdorner);
            ListConnection.Items.SortDescriptions.Add(new SortDescription(field, newDir));
        }

        /// <summary>
        /// ListViewAzureのshort
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SortAzureClick(object sender, RoutedEventArgs e)
        {

            GridViewColumnHeader column = sender as GridViewColumnHeader;
            string field = column.Tag as string;

            if (_CurSortCol != null)
            {
                AdornerLayer.GetAdornerLayer(_CurSortCol).Remove(_CurAdorner);
                ListConnection.Items.SortDescriptions.Clear();
            }

            ListSortDirection newDir = ListSortDirection.Ascending;
            if (_CurSortCol == column && _CurAdorner.Direction == newDir)
                newDir = ListSortDirection.Descending;
            else
                newDir = ListSortDirection.Ascending;


            _CurSortCol = column;
            _CurAdorner = new SortAdorner(_CurSortCol, newDir);
            AdornerLayer.GetAdornerLayer(_CurSortCol).Add(_CurAdorner);
            ListConnection.Items.SortDescriptions.Add(new SortDescription(field, newDir));
        }

        /// <summary>
        /// Cancel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Cancel_Add_Click(object sender, RoutedEventArgs e)
        {
            clear();
            ReturnColor();
            popupAdd.Visibility = Visibility.Hidden;
        }

        /// <summary>
        /// Clear
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Clear_Add_Click(object sender, RoutedEventArgs e)
        {
            clear();
            ReturnColor();
        }


        private void clear()
        {
            //Add
            this.txtAccountName.Text = "";
            this.txtAccountKey.Password = "";
            this.txtContainerName.Text = "";
            this.txtVHDName.Text = "";
            //Edit
            this.txtAccountName_Edit.Text = "";
            this.txtAccountKey_Edit.Password = "";
            this.txtContainerName_Edit.Text = "";
            this.txtVHDName_Edit.Text = "";
        }
        /// <summary>
        /// Validate data Add
        /// </summary>
        /// <returns></returns>
        private bool ValidaData_Add()
        {
            bool Result = true;
            this.txtAccountName.Text = this.txtAccountName.Text.Replace(" ", "");
            this.txtAccountKey.Password = this.txtAccountKey.Password.Replace(" ", "");
            this.txtContainerName.Text = this.txtContainerName.Text.Replace(" ", "");
            this.txtVHDName.Text = this.txtVHDName.Text.Replace(" ", "");

            if (this.txtAccountName.Text.Equals(string.Empty))
            {
                Result = false;
                this.txtAccountName.BorderBrush = Brushes.Red;
            }

            if (this.txtAccountKey.Password.Equals(string.Empty))
            {
                Result = false;
                this.txtAccountKey.BorderBrush = Brushes.Red;
            }

            if (this.txtContainerName.Text.Equals(string.Empty))
            {
                Result = false;
                this.txtContainerName.BorderBrush = Brushes.Red;
            }

            if (this.txtVHDName.Text.Equals(string.Empty))
            {
                Result = false;
                this.txtVHDName.BorderBrush = Brushes.Red;
            }
            return Result;

        }



        /// <summary>
        /// return color
        /// </summary>
        /// <returns></returns>
        private void ReturnColor()
        {
            //Add
            this.txtAccountName.BorderBrush = Brushes.AliceBlue;
            this.txtAccountKey.BorderBrush = Brushes.AliceBlue;
            this.txtContainerName.BorderBrush = Brushes.AliceBlue;
            this.txtVHDName.BorderBrush = Brushes.AliceBlue;

            //Edit
            this.txtAccountName_Edit.BorderBrush = Brushes.AliceBlue;
            this.txtAccountKey_Edit.BorderBrush = Brushes.AliceBlue;
            this.txtContainerName_Edit.BorderBrush = Brushes.AliceBlue;
            this.txtVHDName_Edit.BorderBrush = Brushes.AliceBlue;
        }


        /// <summary>
        /// Add data
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Add_Click(object sender, RoutedEventArgs e)
        {


            if (!ValidaData_Add())
            {
                return;
            }

            VHDDataConfig vhdDataConfig = new VHDDataConfig(this.txtAccountName.Text, this.txtAccountKey.Password, this.txtContainerName.Text, this.txtVHDName.Text);
            List<VHDDataConfig> ListConfig = new List<VHDDataConfig>();



            bool Exist = false;
            if (ListConnection.ItemsSource != null)
                foreach (VHDDataConfig ValidatevhdDataConfig in ListConnection.ItemsSource)
                {

                    if (vhdDataConfig.AccountName.Equals(ValidatevhdDataConfig.AccountName) &&
                        vhdDataConfig.AccountKey.Equals(ValidatevhdDataConfig.AccountKey) &&
                        vhdDataConfig.ContainerName.Equals(ValidatevhdDataConfig.ContainerName) &&
                        vhdDataConfig.VHDName.Equals(ValidatevhdDataConfig.VHDName))
                        Exist = true;

                    ListConfig.Add(ValidatevhdDataConfig);
                }

            if (Exist)
            {
                MessageBox.Show(ResManager.GetString("Error_DataExist" + cons.Language), string.Empty, MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            ListConfig.Add(vhdDataConfig);


            WriteFile(ListConfig);
            ListConnection.ItemsSource = ListConfig;
            clear();
            ReturnColor();
            popupAdd.Visibility = Visibility.Hidden;
        }

        /// <summary>
        /// Add new line to config 
        /// </summary>
        protected void WriteFile(List<VHDDataConfig> ListConfig)
        {

            using (StreamWriter sw = new StreamWriter(Const.FileConfig))
            {
                sw.Write("");
                foreach (VHDDataConfig ValidatevhdDataConfig in ListConfig)
                {
                    sw.WriteLine(ValidatevhdDataConfig.AccountName + " " + ValidatevhdDataConfig.AccountKey + " " + ValidatevhdDataConfig.ContainerName + " " + ValidatevhdDataConfig.VHDName);
                }
                sw.Close();
            }

        }

        /// <summary>
        /// Delete One Line
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Delete_Click(object sender, RoutedEventArgs e)
        {
            MenuItem menu = sender as MenuItem;
            VHDDataConfig vhdDataConfig = menu.DataContext as VHDDataConfig;
            List<VHDDataConfig> ListConfig = new List<VHDDataConfig>();

            if (MessageBox.Show(ResManager.GetString("Info_DeleteFile" + cons.Language), string.Empty, MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No)
                return;

            int count = 0;
            foreach (VHDDataConfig ValidatevhdDataConfig in ListConnection.ItemsSource)
            {
                if (vhdDataConfig.AccountName.Equals(ValidatevhdDataConfig.AccountName) &&
                       vhdDataConfig.AccountKey.Equals(ValidatevhdDataConfig.AccountKey) &&
                       vhdDataConfig.ContainerName.Equals(ValidatevhdDataConfig.ContainerName) &&
                       vhdDataConfig.VHDName.Equals(ValidatevhdDataConfig.VHDName))
                    break;

                count++;
            }
            foreach (VHDDataConfig ValidatevhdDataConfig in ListConnection.ItemsSource)
            {
                ListConfig.Add(ValidatevhdDataConfig);
            }

            ListConfig.RemoveAt(count);


            WriteFile(ListConfig);
            ListConnection.ItemsSource = ListConfig;

        }


        /// <summary>
        /// Cancel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Cancel_Edit_Click(object sender, RoutedEventArgs e)
        {
            clear();
            ReturnColor();
            popupEdit.Visibility = Visibility.Hidden;
        }

        /// <summary>
        /// Clear
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Clear_Edit_Click(object sender, RoutedEventArgs e)
        {
            clear();
            ReturnColor();
        }


        /// <summary>
        /// Validate data Add
        /// </summary>
        /// <returns></returns>
        private bool ValidaData_Edit()
        {
            bool Result = true;
            this.txtAccountName_Edit.Text = this.txtAccountName_Edit.Text.Replace(" ", "");
            this.txtAccountKey_Edit.Password = this.txtAccountKey_Edit.Password.Replace(" ", "");
            this.txtContainerName_Edit.Text = this.txtContainerName_Edit.Text.Replace(" ", "");
            this.txtVHDName_Edit.Text = this.txtVHDName_Edit.Text.Replace(" ", "");


            if (this.txtAccountName_Edit.Text.Equals(string.Empty))
            {
                Result = false;
                this.txtAccountName_Edit.BorderBrush = Brushes.Red;
            }

            if (this.txtAccountKey_Edit.Password.Equals(string.Empty))
            {
                Result = false;
                this.txtAccountKey_Edit.BorderBrush = Brushes.Red;
            }

            if (this.txtContainerName_Edit.Text.Equals(string.Empty))
            {
                Result = false;
                this.txtContainerName_Edit.BorderBrush = Brushes.Red;
            }

            if (this.txtVHDName_Edit.Text.Equals(string.Empty))
            {
                Result = false;
                this.txtVHDName_Edit.BorderBrush = Brushes.Red;
            }
            return Result;

        }

        /// <summary>
        /// Edit data
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Edit_Click(object sender, RoutedEventArgs e)
        {


            if (!ValidaData_Edit())
            {
                return;
            }

            VHDDataConfig vhdDataConfig = new VHDDataConfig(this.txtAccountName_Edit.Text, this.txtAccountKey_Edit.Password, this.txtContainerName_Edit.Text, this.txtVHDName_Edit.Text);
            List<VHDDataConfig> ListConfig = new List<VHDDataConfig>();







            if (ListConnection.ItemsSource != null)
                foreach (VHDDataConfig ValidatevhdDataConfig in ListConnection.ItemsSource)
                {

                    if (this.labAccountName_Edit.Text.Equals(ValidatevhdDataConfig.AccountName) &&
                        this.labAccountKey_Edit.Text.Equals(ValidatevhdDataConfig.AccountKey) &&
                        this.labContainerName_Edit.Text.Equals(ValidatevhdDataConfig.ContainerName) &&
                        this.labVHDName_Edit.Text.Equals(ValidatevhdDataConfig.VHDName))
                        ListConfig.Add(vhdDataConfig);
                    else
                    {
                        ListConfig.Add(ValidatevhdDataConfig);
                    }
                }



            WriteFile(ListConfig);
            ListConnection.ItemsSource = ListConfig;
            clear();
            ReturnColor();
            popupEdit.Visibility = Visibility.Hidden;
        }


        /// <summary>
        /// Delete One Line
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Edit_Open_Click(object sender, RoutedEventArgs e)
        {
            MenuItem menu = sender as MenuItem;
            VHDDataConfig vhdDataConfig = menu.DataContext as VHDDataConfig;


            this.txtAccountName_Edit.Text = vhdDataConfig.AccountName;
            this.txtAccountKey_Edit.Password = vhdDataConfig.AccountKey;
            this.txtContainerName_Edit.Text = vhdDataConfig.ContainerName;
            this.txtVHDName_Edit.Text = vhdDataConfig.VHDName;


            this.labAccountName_Edit.Text = vhdDataConfig.AccountName;
            this.labAccountKey_Edit.Text = vhdDataConfig.AccountKey;
            this.labContainerName_Edit.Text = vhdDataConfig.ContainerName;
            this.labVHDName_Edit.Text = vhdDataConfig.VHDName;



            popupEdit.Visibility = Visibility.Visible;

        }


        private void Close_popupAdd_Click(object sender, RoutedEventArgs e)
        {

            this.Visibility = Visibility.Hidden;
        }


        /// <summary>
        /// TreeView Menu  Language
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ListViewAzureMenu_Opened(object sender, RoutedEventArgs e)
        {
            ResManager = new System.Resources.ResourceManager("AzureDriverExplorer_Client.Properties.Resources", this.GetType().Assembly);

            ContextMenu Menu = (ContextMenu)sender;
            MenuItem item1 = (MenuItem)Menu.Items[0];
            MenuItem item2 = (MenuItem)Menu.Items[1];

            item1.Header = ResManager.GetString("ListConnection_Edit" + cons.Language).Trim();
            item2.Header = ResManager.GetString("ListConnection_Delete" + cons.Language).Trim();

        }
    }



}
